

package com.hx.utils;

import com.hx.entity.*;
import com.hx.service.CallService;
import com.hx.service.SendService;

import java.io.*;
import java.util.*;

public class CardUtils implements Serializable{
    public static Map<String, MobileCard> cards=new HashMap<String, MobileCard>(  );
    // 所有卡号的消费记录列表
    public static Map<String, List<ConsumInfo>> consumInfos = new HashMap<String, List<ConsumInfo>>();

        File file = new File("E:\\savedata.dat");
        public void saveData() {
            try {
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
                oos.writeObject(cards);
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
         //读取
        public void loadData() {
            if(file.length()!=0){
                try {
                    ObjectInput oi = new ObjectInputStream(new FileInputStream(file));
                    cards = (Map<String, MobileCard>)oi.readObject();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }




     //用户初始化
    public void intitScene() {
        MobileCard hl = new MobileCard( "123", "话唠", "123", new TalkPackage(), 88, 300, 89, 88, 90 ); //话唠套餐
        MobileCard wc = new MobileCard( "13945674567", "网虫", "123", new NetPackage(), 99, 300, 200, 60, 20 ); //网虫套餐
        MobileCard cr = new MobileCard( "13978917891", "超人", "123", new SuperPackage(), 100, 400, 50, 20, 900 ); //超人套餐

        CardUtils.cards.put( "123", hl );  //添加到集合里
        CardUtils.cards.put( "13945674567", wc );  //添加到集合里
        CardUtils.cards.put( "13978917891", cr );  //添加到集合里

   /*     ConsumInfo info = new ConsumInfo( "12345678910", "电话", 500 );
        List<ConsumInfo> list = new ArrayList<ConsumInfo>();
        list.add( info );
        consumInfos.put( info.getCardNumber(), list );*/

    }
//登录验证
   public boolean isExistCard(String number, String passWord) {
        if (cards.containsKey(number)&&(cards.get(number).getPassWord().equals(passWord))) {
            return true;
        }
        System.out.println("登录失败!");
        return false;

    }
//验证号码
    public boolean isExistCard(String number) {
        Set<String>	numbers=cards.keySet();
        Iterator<String> iterator=numbers.iterator();
        while (iterator.hasNext()) {
            String str=iterator.next();
            if (str.equals(number))
                return true;
        }
        return false;
    }
    public String createNumber() {
        Random random = new Random();
        boolean isExist = false;
        String number = "";
        int temp = 0;
        do {
            isExist = false;
            do {
                temp = random.nextInt( 100000000 );
            } while (temp < 10000000);
            //生成之前，前面加“139”
            number = "139" + temp;
            //和现有用户的卡号比较，不能是重复的
            if (cards != null) {
                Set<String> cardNumbers = cards.keySet();
                for (String cardNumber : cardNumbers) {
                    if (number.equals( cardNumber )) {
                        isExist = true;
                        break;
                    }
                }
            }
        } while (isExist);
        return number;
    }

    public String[] getNewNumber(int count) {
        String[] strs = new String[count];
        for (int i = 0; i < count; i++) {
            strs[i] = createNumber();  //通过随机生成给strs[i]赋值
        }
        return strs;
    }
    //注册新卡
    public void addCard(MobileCard card) {
        cards.put( card.getCardnumber(), card );

    }
    //删除卡号
    public void delCard(String number) {
        if (cards.containsKey( number )) {
            cards.remove( number ); //移除手机号
            System.out.println( "卡号:" + number + "办理退网成功！" );
            System.out.println( "谢谢使用！" );
        } else {
            System.out.println( "手机号码输入有误！" );
        }
    }
    //本月账单查询
    public void showAmountDetail(String number) {
        StringBuffer mg = new StringBuffer();
        MobileCard card = cards.get( number);    //要查询的卡
        mg.append( "您的卡号:" + card.getCardnumber() + "当月账单:\n" );
        mg.append( "套餐资费:" + card.getSerPackage().getPrice() + "元\n" );
        mg.append( "合计:" + card.getConsumAmont()  + "元\n" );
        mg.append( "账号余额:" +  card.getMonery()  + "元" );
        System.out.println( mg );
    }

    public void addConsumInfo(String number, ConsumInfo info) {
        if (consumInfos.containsKey(number)) {
            consumInfos.get(number).add(info);
        }else{
            List<ConsumInfo> list = new ArrayList<ConsumInfo>();
            list.add(info);
            consumInfos.put(number, list);
        }
    }
    //套餐余额查询
    public void showRemainDetail(String number) {
        MobileCard card = cards.get( number );
        int remainTalkTime;
        int remainSmsCount;
        double remainFlow;
        StringBuffer meg = new StringBuffer();
        meg.append( "您的卡号是" + number + ",套餐内剩余:\n" );
        ServicePackage pack = card.getSerPackage();
        if (pack instanceof TalkPackage) {
            //向下转型为话唠套餐对象
            TalkPackage cardPack = (TalkPackage) pack;
            //话唠套餐，查询套餐内剩余的通话时长和短信条数
            remainTalkTime = cardPack.getTalkTime() > card.getRealTalkTime() ? cardPack.getTalkTime()
                    - card.getRealTalkTime() : 0;
            meg.append( "通话时长:" + remainTalkTime + "分钟\n" );
            remainSmsCount = cardPack.getSmsCount() > card.getRealSMSCount() ? cardPack.getSmsCount()
                    - card.getRealSMSCount() : 0;
            meg.append( "短信条数:" + remainSmsCount + "条" );
        } else if (pack instanceof NetPackage) {
            //向下转型为网虫套餐的信息
            NetPackage netPackage = (NetPackage) pack;
            remainFlow = netPackage.getFlow() * 1024 > card.getRealFlow() ? netPackage.getFlow() * 1024
                    - card.getRealFlow() : 0;
            meg.append( "上网流量:" + remainFlow / 1024  + "GB" );
        } else {
            SuperPackage superPackage = (SuperPackage) pack;
            remainTalkTime = superPackage.getTalkTime() > card.getRealTalkTime() ? superPackage.getTalkTime()
                    - card.getRealTalkTime() : 0;
            meg.append( "通话时长:" + remainTalkTime + "分钟\n" );
            remainSmsCount = superPackage.getSmsCount() > card.getRealSMSCount() ? superPackage.getSmsCount()
                    - card.getRealSMSCount() : 0;
            meg.append( "短信条数:" + remainSmsCount + "条" );
            remainFlow = superPackage.getFlow() * 1024 > card.getRealFlow() ? superPackage.getFlow() * 1024
                    - card.getRealFlow() : 0;
            meg.append( "上网流量:" +remainFlow / 1024  + "GB" );
        }
        System.out.println( meg );
    }


//使用嗖嗖
Map<Integer, Scene> scenes= new HashMap<Integer, Scene>();

    Scene scene0 = new Scene("通话", 90, "问候客户，谁知其如此难缠，通话90分钟");
    Scene scene1 = new Scene("通话", 30, "询问妈妈身体状况，本地通话30分钟");
    Scene scene2 = new Scene("短信", 5, "参与环境保护实施方案问卷调查，发送短信5条");
    Scene scene3 = new Scene("短信", 50, "通知朋友手机换号，发送短信50条");
    Scene scene4 = new Scene("上网", 1024, "和女朋友用微信视频聊天，使用流量1GB");
    Scene scene5 = new Scene("上网", 2 * 1024, "晚上手机在线看韩剧，不留神睡着啦！使用2GB");
    public void userSoso(String number) {
        scenes.put(0, scene0);
        scenes.put(1, scene1);
        scenes.put(2, scene2);
        scenes.put(3, scene3);
        scenes.put(4, scene4);
        scenes.put(5, scene5);


        MobileCard card = cards.get( number );    //获取此卡对象
        ServicePackage pack = card.getSerPackage();    //获取此卡所属套餐
        Random random = new Random();
        int ranNum = 0;
        int temp = 0;    //记录个场景中实际消费
        do {
            ranNum = random.nextInt(6);
            Scene scene = scenes.get( ranNum ); //获取该序号所对应的场景
            switch (ranNum) {
                case 0:
                case 1:
                    //序号为0或1为通话场景
                    //判断该卡所属套餐是否支持通话功能
                    if (pack instanceof CallService) {
                        //执行通话方法
                        System.out.println( scene.getDescription() );
                        CallService callService = (CallService) pack;
                        try {
                            temp = callService.call( scene.getData(), card );
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //添加一条消费记录
                        addConsumInfo( number, new ConsumInfo( number, scene.getType(), temp ) );
                        break;
                    } else {
                        //如果该卡套餐不支持通话功能，则重新生成随机数选择其他场景
                        continue;
                    }
                case 2:
                case 3:
                    //判断该卡所属套餐是否支持短信功能
                    if (pack instanceof SendService) {
                        //执行短信方法
                        System.out.println( scene.getDescription() );
                        SendService sendService = (SendService) pack;
                        try {
                            temp = sendService.send( scene.getData(), card );
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //添加一条消费记录
                        addConsumInfo( number, new ConsumInfo( number, scene.getType(), temp ) );
                        break;
                    } else {
                        //如果该卡套餐不支持通话功能，则重新生成随机数选择其他场景
                        continue;
                    }
                case 4:
                case 5:
                    //判断该卡所属套餐是否支持上网功能
                    if (pack instanceof NetPackage) {
                        //执行上网方法
                        System.out.println( scene.getDescription() );
                        NetPackage netPackage = (NetPackage) pack;
                        try {
                            temp = netPackage.netPlay( scene.getData(), card );
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //添加一条消费记录
                        addConsumInfo( number, new ConsumInfo( number, scene.getType(), temp ) );
                        break;
                    } else {
                        //如果该卡套餐不支持通话功能，则重新生成随机数选择其他场景
                        continue;
                    }
            }
            break;
        } while (true);


    }

//资费说明
    public void showDescription() {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            //创建一个FileReader对象
            fr = new FileReader("D://套餐资费说明.txt");
            //创建一个BufferedReader对象
            br = new BufferedReader(fr);
            //读取一行数据
            String line = null;
            while((line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(br != null){
                    br.close();
                }
                if(fr != null){
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }
   //更换套餐
    public void changingPack(String number) {
        Scanner scanner=new Scanner( System.in );
        System.out.println( "1.话唠套餐 2.网虫套餐 3.超人套餐 ：请选择(序号)：" );
        int p= scanner.nextInt();
        switch (p) {
            case 1:  //选择变更的套餐为话唠套餐
                if (cards.get( number ).getSerPackage() instanceof TalkPackage) {
                    System.out.println( "对不起，您已经是该套餐用户，无需换套餐！" );
                } else {
                    if (cards.get( number ).getMonery() < cards.get( number ).getSerPackage().getPrice()) {//如果剩余费用不够支持新的套餐费用
                        System.out.println( "对不起,您的的余额不足以支付新的套餐本月资费，请充值后再办理业务！" );
                    } else {
                        cards.get( number ).setRealSMSCount( 0 );
                        cards.get( number ).setRealTalkTime( 0 );
                        cards.get( number ).setRealFlow( 0 );
                        cards.get( number ).setSerPackage( createPackage( p ) );
                        System.out.println( "套餐更换成功！" );
                        createPackage( p).showInfo();
                    }
                }
                break;
            case 2: //选择变更的套餐为网虫套餐
                if (cards.get( number ).getSerPackage() instanceof NetPackage) {
                    System.out.println( "对不起，您已经是该套餐用户，无需换套餐！" );
                } else {
                    if (cards.get( number ).getMonery()< cards.get( number ).getSerPackage().getPrice()) {//如果剩余费用不够支持新的套餐费用
                        System.out.println( "对不起,您的的余额不足以支付新的套餐本月资费，请充值后再办理业务！" );
                    } else {
                        cards.get( number ).setRealSMSCount( 0 );
                        cards.get( number ).setRealTalkTime( 0 );
                        cards.get( number ).setRealFlow( 0 );
                        cards.get( number ).setSerPackage( createPackage(p ) );
                        System.out.println( "套餐更换成功！" );
                        createPackage( p).showInfo();
                    }
                }
                break;
            case 3://选择变更的套餐为超人套餐
                if (cards.get( number ).getSerPackage() instanceof SuperPackage) {
                    System.out.println( "对不起，您已经是该套餐用户，无需换套餐！" );
                } else {
                    if (cards.get( number ).getMonery() < cards.get( number ).getSerPackage().getPrice()) {//如果剩余费用不够支持新的套餐费用
                        System.out.println( "对不起,您的的余额不足以支付新的套餐本月资费，请充值后再办理业务！" );
                    } else {
                        cards.get( number ).setRealSMSCount( 0 );
                        cards.get( number ).setRealTalkTime( 0 );
                        cards.get( number ).setRealFlow( 0 );
                        cards.get( number ).setSerPackage( createPackage( p) );
                        System.out.println( "套餐更换成功！" );
                        createPackage( p).showInfo();
                    }
                }
                break;
        }


    }
//打印消费信息
    public void printConsumIofo(String number) {
        Writer fileWriter = null;
        try {
            try {
                fileWriter = new FileWriter( "D://consumes.txt" );
            } catch (IOException e) {
                e.printStackTrace();
            }
            Set<String> numbers = consumInfos.keySet();
            Iterator<String> it = numbers.iterator();
            List<ConsumInfo> infos = new ArrayList<ConsumInfo>();
            infos = consumInfos.get( number );
            //存储指定卡的所有消费记录
            //现有消费列表中是否存在此卡号的消费记录，是：true 否：false
            boolean isExist = false;
            while (it.hasNext()) {
                String numberKey = it.next();
                if (number.equals( numberKey )) {
                    isExist = true;
                }/*else{   //如果
                    isExist = false;
                }*/

            }

            if (isExist) {
                StringBuffer content = new StringBuffer( "***********" + number + "消费记录************\n" );
                content.append( "序号\t类型\t数据（通话（分钟）/上网（MB）/短信（条））\n" );
                for (int i = 0; i < infos.size(); i++) {
                    ConsumInfo info = infos.get( i );
                    System.out.println( (i + 1) + ".\t" + info.getType() + "\t" + info.getConsumData() + "\n" );
                    content.append( (i + 1) + ".\t" + info.getType() + "\t" + info.getConsumData() + "\n" );
                }
                fileWriter.write( content.toString() );
                fileWriter.flush();
                System.out.println( "消息记录打印完毕！" );
            } else {
                System.out.println( "对不起，不存在此号码的消费记录，不能够打印！" );
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
//话费充值
    public void moneyRecharge() {
        CardUtils cardUtils=new CardUtils();
        Scanner scanner =new Scanner( System.in );
        System.out.println("请输入手机卡号：");
        String strNum=scanner.next();
        boolean is=cardUtils.isExistCard(strNum);
        if (is) {
            System.out.println("请输入充值余额：");
                double strMoney=scanner.nextDouble();
            cardUtils.changeMoney(strNum,strMoney);
            System.out.println("充值成功,当前话费余额为"+CardUtils.cards.get(strNum).getMonery()+"元");
        }else {
            System.out.println("手机输入有误，请重新输入手机号：");
        }

    }

    private void changeMoney( String  number,double money) {
        cards.get(number).setMonery(cards.get(number).getMonery()+money);
    }


    public ServicePackage createPackage(int packId) {
        ServicePackage servicePackage = null;
        switch (packId) {
            case 1:
                servicePackage = new TalkPackage();
                break;
            case 2:
                servicePackage = new NetPackage();
                break;
            case 3:
                servicePackage = new SuperPackage();
                break;
            default:
                break;
        }
        return servicePackage;
    }


}

